﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BitAuto.EP.CRMLogSystem.Utils;
using System.Threading.Tasks;
using System.IO;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Linq;
using System.Threading;
using BitAuto.EP.Plat.Util;

namespace CRMSimple.LogServices
{
    public class DeleteFileProcess
    {
        public string DirectoryPath { get { return AppConfig.GetAppSetting("TextFileDataCache:Directory"); } }
        public string Extension { get { return AppConfig.GetAppSetting("TextFileDataCache:Extension"); } }
        private ConfigurationManager config = Singleton<ConfigurationManager>.Instance;
        public string FileRule { get { return AppConfig.GetAppSetting("TextFileDataCache:FileRule"); } }
        public int SleepTime { get { return EConvert.ToInt(AppConfig.GetAppSetting("DeleteFile:SleepTime"), 6000); } }
        private CancellationTokenSource cts = new CancellationTokenSource();
        private bool isStop = false;
        //private TextFileDataCache cahe = Singleton<TextFileDataCache>.Instance;

        private Action<object> _run;
        public Action<object> Run
        {
            get
            {
                if (_run==null)
                 _run =(e) =>
                {
                    while (!isStop)
                    {
                        try
                        {
                            //获取当前所有的文件列表
                            var path=Path.Combine(AppDomain.CurrentDomain.BaseDirectory, DirectoryPath);
                            if (Directory.Exists(path))
                            {
                                var files = Directory.GetFiles(path, "*." + Extension, SearchOption.AllDirectories);
                                //获取不删除的文件列表
                                IList<string> notDeleteFiles = GetNotDeleteFiles();
                                string name = string.Empty
                                    , dir = string.Empty; ;
                                foreach (var file in files)
                                {
                                    name = Path.GetFileName(file);
                                    //如果是可删除的删除
                                    if ((File.GetAttributes(file) & FileAttributes.Archive) == FileAttributes.Archive)
                                    //if (!notDeleteFiles.Contains(name) && GetCurCountInFileName(Path.GetFileName(item)) < GetCurCountInFileName(config[GetKeyInFileName(name), "ReadFileName"]))
                                    {
                                        path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, file);
                                        //DataLogHelper.M("删除了" + path);
                                        LogExceptionRoot.DelelteFileLog.Info("删除了" + path);
                                        File.Delete(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, file));
                                    }
                                    //将异常文件移到异常文件夹
                                    if ((File.GetAttributes(file) & FileAttributes.Device) == FileAttributes.Device)
                                    {
                                        dir = Path.Combine(path, "ErrorFile");
                                        if (!Directory.Exists(dir))
                                            Directory.CreateDirectory(dir);
                                       
                                         File.Move(file, Path.Combine(path, "ErrorFile", GetKeyInFileName(name), name));
                                        
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            string content = string.Format("删除数据异常");
                            //DataLogHelper.E(content, ex);
                            LogExceptionRoot.DelelteFileLog.Info(content, ex);
                            ErrorAlertMailHelper.SendAlertMail("日志服务入库异常", content + "异常：" + ex.Message + ex.StackTrace);
                        }
                      
                        Thread.Sleep(SleepTime);
                    }

                };//, cts.Token, TaskCreationOptions.AttachedToParent);
                return _run;
            }
        }
        public void Stop()
        {
            isStop = true;
            //cts.Cancel();
            //this._run.Dispose();
        }

        private IList<string> GetNotDeleteFiles()
        {
            List<string> list = new List<string>();
            foreach (var item in config.AppSettings)
            {
                list.Add(item.Value["WriteFileName"]);
                list.Add(item.Value["ReadFileName"]);
                list.AddRange(GetFiles(item.Value["ErrorFiles"]));
            }
            return list.Distinct().ToList();
        }

        private string[] GetFiles(string data)
        {
            if (string.IsNullOrEmpty(data)) return null;
            JArray arry = JArray.Parse(data);
            return (from s in arry
                    select (string)s
                        ).ToArray();
        }
        private int GetCurCountInFileName(string fileName)
        {
            if (string.IsNullOrEmpty(fileName) || !Regex.IsMatch(fileName, Regex.Replace(FileRule, "{.+}", ".+"))) return -1;

            return EConvert.ToInt(fileName.Split('_')[1].Split('.')[0]);
        }
        private string GetKeyInFileName(string fileName)
        {
            if (string.IsNullOrEmpty(fileName) || !Regex.IsMatch(fileName, Regex.Replace(FileRule, "{.+}", ".+"))) return string.Empty;

            return fileName.Split('_')[0];
        }
    }
}
